package dao;

import entity.Product;
import utils.DBUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品类的DAO方法
 */
public class ProductDAO {
    public List<Product> queryAllProduct() {
        List<Product> productList = null;
        String sql = "select * from products";

        Connection conn = DBUtils.getConnection();
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            productList = new ArrayList<>();
            while ( rs.next() ) {
                Product pro = new Product();
                pro.setId(rs.getInt(1));
                pro.setName(rs.getString(2));
                pro.setPrice(rs.getDouble(3));
                pro.setCount(rs.getInt(4));

                productList.add(pro);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return productList;
    }

    /**
     * 修改商品的数量
     * @param count
     */
    public Integer modifyGoodsNumber(int count, int pid ) {
        int result = 0;
        String sql = "UPDATE PRODUCTS SET PRODUCTCOUNT = PRODUCTCOUNT-? WHERE PRODUCTID=?";
        Connection conn = DBUtils.getConnection();
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(sql);
            pst.setInt(1,count);
            pst.setInt(2,pid);
            result = pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}
